package org.csu.onlineedubackend.mapper;

import org.apache.ibatis.annotations.*;
import org.csu.onlineedubackend.entity.FriendRequest;
import org.csu.onlineedubackend.entity.User;

import java.util.List;

@Mapper
public interface FriendRequestMapper {
    
    @Insert("INSERT INTO friend_requests (sender_id, receiver_id, status, created_at, updated_at) " +
            "VALUES (#{senderId}, #{receiverId}, #{status}, NOW(), NOW()) " +
            "ON DUPLICATE KEY UPDATE status = #{status}, updated_at = NOW()")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(FriendRequest friendRequest);
    
    @Select("SELECT * FROM friend_requests WHERE id = #{id}")
    FriendRequest findById(Long id);
    
    @Select("SELECT * FROM friend_requests WHERE sender_id = #{senderId} AND receiver_id = #{receiverId}")
    FriendRequest findBySenderAndReceiver(@Param("senderId") Integer senderId, @Param("receiverId") Integer receiverId);
    
    @Select("SELECT * FROM friend_requests WHERE receiver_id = #{receiverId} AND status = 'PENDING' ORDER BY created_at DESC")
    List<FriendRequest> findPendingByReceiverId(Integer receiverId);
    
    @Select("SELECT * FROM friend_requests WHERE receiver_id = #{receiverId} ORDER BY created_at DESC")
    List<FriendRequest> findAllByReceiverId(Integer receiverId);
    
    @Select("SELECT * FROM friend_requests WHERE sender_id = #{senderId}")
    List<FriendRequest> findBySenderId(Integer senderId);
    
    @Update("UPDATE friend_requests SET status = #{status}, updated_at = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") String status);
    
    @Delete("DELETE FROM friend_requests WHERE id = #{id}")
    int delete(Long id);
    
    @Select("SELECT u.* FROM users u " +
            "JOIN friend_requests fr ON u.id = fr.sender_id " +
            "WHERE fr.receiver_id = #{receiverId} AND fr.status = 'PENDING'")
    List<User> findRequestUsersByReceiverId(Integer receiverId);
} 